package com.nwcl.basic.service.impl;

import com.nwcl.basic.bo.GoodsBO;
import com.nwcl.basic.bo.GoodsSpaceBO;
import com.nwcl.basic.dao.GoodsSpaceDao;
import com.nwcl.basic.entity.GoodsSpace;
import com.nwcl.basic.service.GoodsSpaceService;
import com.nwcl.common.exception.CustomException;
import com.nwcl.common.utils.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * @author liguiqin
 * @date 2023/5/26
 */
@Service
public class GoodsSpaceServiceImpl implements GoodsSpaceService {
    @Autowired
    private GoodsSpaceDao goodsSpaceDao;

    @Override
    public GoodsSpaceBO getByGoodsId(Integer goodsId) {
        List<GoodsSpace> modelList = goodsSpaceDao.listByGoodsIds(Arrays.asList(goodsId));
        if (CollectionUtils.isEmpty(modelList)) {
            return null;
        }
        return BeanUtil.copy(modelList.get(0), GoodsSpaceBO.class);
    }

    @Override
    public synchronized void deduction(GoodsBO goodsBO, Integer userId, BigDecimal userIntegral,Integer num) throws CustomException {
        GoodsSpaceBO goodsSpaceBO = this.getByGoodsId(goodsBO.getId());
        //1.校验库存是否足够
        if (goodsSpaceBO == null) {
            throw new CustomException("商品无库存,不可兑换");
        }
        //2.校验用户积分是否足够
        if (userIntegral.compareTo(goodsBO.getIntegral()) < 0) {
            throw new CustomException("用户积分不足,不可兑换");
        }
        //3.计算剩余库存
        int inventory = goodsSpaceBO.getInventory() - num;
        if (0 > inventory) {
            throw new CustomException("商品无库存,不可兑换");
        }
        //4.更新商品库存
        goodsSpaceDao.updateInventoryByGoodsId(goodsBO.getId(), inventory);
    }
}
